<template>
  <div class="science-page">
    <div class="page-header">
      <h2>科普文章管理</h2>
      <el-button type="primary" @click="handleCreateArticle">
        新增文章
      </el-button>
    </div>

    <!-- 文章列表 -->
    <div class="article-list" v-loading="loading">
      <el-table :data="articleList" style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="title" label="标题" min-width="200" />
        <el-table-column prop="category" label="分类" width="120">
          <template #default="{ row }">
            {{ categoryOptions.find(opt => opt.value === row.category)?.label || row.category }}
          </template>
        </el-table-column>
        <el-table-column prop="description" label="简介" min-width="300" show-overflow-tooltip />
        <el-table-column prop="views" label="浏览量" width="100" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 1 ? 'success' : 'info'">
              {{ row.status === 1 ? '已发布' : '已下架' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleEdit(row)">编辑</el-button>
            <el-button 
              link 
              :type="row.status === 1 ? 'warning' : 'success'"
              @click="handleToggleStatus(row)"
            >
              {{ row.status === 1 ? '下架' : '发布' }}
            </el-button>
            <el-button link type="danger" @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 文章编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="editingArticle.id ? '编辑文章' : '新增文章'"
      width="70%"
      :close-on-click-modal="false"
      destroy-on-close
    >
      <el-form 
        ref="formRef"
        :model="editingArticle"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="标题" prop="title">
          <el-input 
            v-model="editingArticle.title"
            placeholder="请输入文章标题"
            maxlength="100"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="分类" prop="category">
          <el-select 
            v-model="editingArticle.category"
            placeholder="请选择文章分类"
            style="width: 100%"
          >
            <el-option
              v-for="option in categoryOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="简介" prop="description">
          <el-input
            v-model="editingArticle.description"
            type="textarea"
            :rows="3"
            placeholder="请输入文章简介"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="封面" prop="cover">
          <div class="upload-wrapper">
            <el-upload
              class="article-cover"
              :http-request="handleCoverUpload"
              :before-upload="beforeCoverUpload"
            >
              <img v-if="editingArticle.cover" :src="editingArticle.cover" class="cover-preview">
              <el-icon v-else class="upload-icon"><Plus /></el-icon>
              <div class="upload-text">
                <span>点击上传封面</span>
                <div class="upload-tip">建议尺寸：800x400px，支持 jpg、png 格式</div>
              </div>
            </el-upload>
          </div>
        </el-form-item>

        <el-form-item label="内容" prop="content">
          <el-input
            v-model="editingArticle.content"
            type="textarea"
            :rows="10"
            placeholder="请输入文章内容"
            maxlength="5000"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="状态">
          <el-radio-group v-model="editingArticle.status">
            <el-radio :label="0">下架</el-radio>
            <el-radio :label="1">发布</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" :loading="submitting" @click="handleSubmit">
            保存
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getScienceList, createScience, updateScience, deleteScience, updateScienceStatus } from '@/api/science'
import { Plus } from '@element-plus/icons-vue'
import dayjs from 'dayjs'
import { initOSSClient, validateFile } from '@/utils/oss'
import {uploadAvatar, uploadImg} from "@/api/user.js";

// 列表数据
const loading = ref(false)
const articleList = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 对话框控制
const dialogVisible = ref(false)
const submitting = ref(false)
const formRef = ref(null)

// 编辑的文章数据
const editingArticle = reactive({
  id: '',
  title: '',
  category: '',
  description: '',
  content: '',
  cover: '',
  status: 1
})

// 文章分类选项
const categoryOptions = [
  { value: 'growth', label: '生长发育' },
  { value: 'nutrition', label: '营养饮食' },
  { value: 'disease', label: '疾病预防' },
  { value: 'mental', label: '心理健康' }
]

// 表单校验规则
const rules = {
  title: [
    { required: true, message: '请输入标题', trigger: 'blur' },
    { max: 100, message: '标题长度不能超过100个字符', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择文章分类', trigger: 'change' }
  ],
  description: [
    { required: true, message: '请输入文章简介', trigger: 'blur' },
    { max: 200, message: '简介长度不能超过200个字符', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入内容', trigger: 'blur' },
    { max: 5000, message: '内容长度不能超过5000个字符', trigger: 'blur' }
  ]
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return '--'
  return dayjs(date).format('YYYY-MM-DD HH:mm:ss')
}

// 获取文章列表
const fetchArticleList = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value
    }
    const res = await getScienceList(params)
    if (res && Array.isArray(res.records)) {
      articleList.value = res.records
      total.value = res.total
    }
  } catch (error) {
    console.error('获取文章列表失败:', error)
    ElMessage.error('获取文章列表失败')
  } finally {
    loading.value = false
  }
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchArticleList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchArticleList()
}

// 新增文章
const handleCreateArticle = () => {
  Object.assign(editingArticle, {
    id: '',
    title: '',
    category: '',
    description: '',
    content: '',
    cover: '',
    status: 1
  })
  dialogVisible.value = true
}

// 编辑文章
const handleEdit = (row) => {
  Object.assign(editingArticle, row)
  dialogVisible.value = true
}

// 切换文章状态
const handleToggleStatus = async (row) => {
  try {
    await updateScienceStatus(row.id, row.status === 1 ? 0 : 1)
    ElMessage.success('操作成功')
    fetchArticleList()
  } catch (error) {
    console.error('操作失败:', error)
    ElMessage.error('操作失败')
  }
}

// 删除文章
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确定要删除这篇文章吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await deleteScience(row.id)
      ElMessage.success('删除成功')
      fetchArticleList()
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {})
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (!valid) {
      ElMessage.warning('请完善表单信息')
      return
    }
    
    submitting.value = true
    try {
      if (editingArticle.id) {
        await updateScience(editingArticle)
      } else {
        await createScience(editingArticle)
      }
      ElMessage.success('保存成功')
      dialogVisible.value = false
      fetchArticleList()
    } catch (error) {
      console.error('保存失败:', error)
      ElMessage.error('保存失败')
    } finally {
      submitting.value = false
    }
  })
}

// 封面上传相关方法
const handleCoverUpload = async ({ file }) => {
  try {
    console.log('开始上传封面:', {
      fileName: file.name,
      fileSize: (file.size / 1024 / 1024).toFixed(2) + 'MB',
      fileType: file.type
    })

    // 验证文件
    await validateFile(file, {
      maxSize: 5 * 1024 * 1024, // 5MB
      allowedTypes: ['image/jpeg', 'image/png']
    })

    // 生成OSS存储路径
    const filePath = `science/covers/${Date.now()}-${file.name}`
    
    // 上传到OSS
    const fileUrl = await uploadImg(file, { path: filePath })
    
    // 更新表单数据
    editingArticle.cover = fileUrl
    ElMessage.success('封面上传成功')

  } catch (error) {
    console.error('封面上传失败:', error)
    ElMessage.error('封面上传失败：' + error.message)
    throw error
  }
}

// 上传前校验
const beforeCoverUpload = (file) => {
  try {
    validateFile(file, {
      maxSize: 5 * 1024 * 1024, // 5MB
      allowedTypes: ['image/jpeg', 'image/png']
    })
    return true
  } catch (error) {
    ElMessage.error(error.message)
    return false
  }
}

// 初始化
onMounted(() => {
  fetchArticleList()
  initOSSClient()
})
</script>

<style scoped>
.science-page {
  padding: 24px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0;
  font-size: 24px;
  color: #333;
}

.article-list {
  background: #fff;
  padding: 24px;
  border-radius: 4px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

:deep(.el-dialog__body) {
  padding: 20px 40px;
}

.upload-wrapper {
  width: 100%;
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  overflow: hidden;
  &:hover {
    border-color: var(--el-color-primary);
  }
}

.article-cover {
  cursor: pointer;
  position: relative;
  display: flex;
  justify-content: center;
  align-items: center;
  height: 200px;
  background-color: #fafafa;
  
  .cover-preview {
    height: 100%;
    width: 100%;
    object-fit: cover;
  }
  
  .upload-icon {
    font-size: 28px;
    color: #8c939d;
  }
  
  .upload-text {
    color: #8c939d;
    font-size: 14px;
    text-align: center;
    margin-top: 8px;
    
    .upload-tip {
      font-size: 12px;
      margin-top: 4px;
      color: #999;
    }
  }
  
  &:hover {
    background-color: #f5f7fa;
  }
}
</style> 